package com.zf.easyexcel.utils.handler;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.BuiltinFormats;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Sheet;

import java.io.File;
import java.util.*;

/**
 * 设置表格中 列 的数据格式，对该列的所有行都生效
 */
public class CustomColumnDataFormatWriteHandler implements SheetWriteHandler {
    /**
     * 每列对应的格式，Excel内置格式可以在 {@link BuiltinFormats#_formats} 中查看，也可以自定义。
     * 列索引(>=0) -> 数据格式
     */
    private final Map<Integer, String> columnStyleMap;

    public CustomColumnDataFormatWriteHandler(Map<Integer, String> columnStyleMap) {
        if (columnStyleMap == null || columnStyleMap.isEmpty()) {
            columnStyleMap = Collections.emptyMap();
        }
        this.columnStyleMap = columnStyleMap;
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        DataFormat dataFormatter = writeWorkbookHolder.getWorkbook().createDataFormat();
        Sheet sheet = writeSheetHolder.getSheet();
        for (Map.Entry<Integer, String> entry : columnStyleMap.entrySet()) {
            Integer columnIndex = entry.getKey();
            String format = entry.getValue();

            // 创建样式
            CellStyle cellStyle = writeWorkbookHolder.getWorkbook().createCellStyle();
            // 设置数据格式
            cellStyle.setDataFormat(dataFormatter.getFormat(format));
            // 设置整列的默认样式
            sheet.setDefaultColumnStyle(columnIndex, cellStyle);
        }
    }


    public static void main(String[] args) {
        // 表头
        List<List<String>> headers = new ArrayList<>();
        headers.add(Collections.singletonList("超级长长长长长长长长表头1"));
        headers.add(Collections.singletonList("超级长长长长长长长长表头2"));

        // 列样式
        HashMap<Integer, String> columnStyleMap = new HashMap<>();
        columnStyleMap.put(0, "@"); // 文本
        columnStyleMap.put(1, "yyyy-mm-dd"); // 日期

        // 一行数据
        HashMap<Integer, String> oneRow = new HashMap<>();
        oneRow.put(0, "111");
        oneRow.put(1, "2025-12-10");

        EasyExcel.write(new File("D:\\test.xlsx"))
                .sheet(0)
                .head(headers)
                .registerWriteHandler(new CustomColumnDataFormatWriteHandler(columnStyleMap))
                .registerWriteHandler(new CustomAutoColumnWidthWriteHandler())
                .doWrite(Collections.singletonList(oneRow));
    }
}
